package com.stlm2.controller;

import com.google.gson.Gson;
import com.stlm2.core.oauth.*;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.entity.OAuthType;
import com.stlm2.dems.entity.User;
import com.stlm2.dems.sns.entity.Platform;
import com.stlm2.dems.sns.service.SmsService;
import com.stlm2.dems.user.entity.UserState;
import com.stlm2.dems.user.entity.UserType;
import com.stlm2.dems.service.UserService;
import com.stlm2.util.Memcached;

import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * Author：fuchunyu
 * Date：2017/10/11
 * Description：授权登录
 */
@Controller
@RequestMapping("/OAuth")
public class OAuthController {

    @Resource
    private UserService userService;
    @Resource
    private Memcached memcached;
    @Resource
    private SmsService smsService;
    @Resource
    private UserDao userDao;

    /**
     *
     * @param code
     * @param state
     * @return WEB授权判断是否已经绑定授权过
     */
    @ResponseBody
    @RequestMapping(value = "/OAuthIsRegist2.json",produces = "application/json;charset=utf-8")
    public String OAuthIsRegist2(String companyCode,String code,String state){
        ModelMap map=new ModelMap();
        User user=null;
        String accessToken=null;
        String openId=null;
        System.out.println("code"+code+"state"+state);
        if (!"authdeny".equals(code)) {
            if(OAuthType.WX.toString().equals(state)) {
                // 获取网页授权access_token
                WeixinOauth2Token weixinOauth2Token = AdvancedUtil.getWxAccessToken("wxcae7693294154eb4", "1bad93acbef98bcec9c564badb4c2e32", code);
                if (weixinOauth2Token == null)
                    return CodeContent.returnFailure("获取accessToken失败！");
                // 网页授权接口访问凭证
                accessToken = weixinOauth2Token.getAccessToken();
                System.out.println("accessToken" + accessToken);
                if (StringUtils.isEmpty(accessToken))
                    return CodeContent.returnFailure("获取accessToken失败！");
                // 用户标识
                 openId = weixinOauth2Token.getOpenId();
                System.out.println("openId" + openId);
                // 获取用户信息
                WxUserInfo snsUserInfo = AdvancedUtil.getWxUserInfo(accessToken, openId);
                System.out.println("snsUserInfo" + snsUserInfo.toString());
                if (snsUserInfo == null)
                    return CodeContent.returnFailure("获取微信用户信息失败！");

                 user = userService.getByWxOpenID(snsUserInfo.getUnionid());
            }else if(OAuthType.QQ.toString().equals(state)){
                // 获取网页授权access_token
                QqOauth2Token qqAccessToken = AdvancedUtil.getQqAccessToken("101442252", "2b3d1944b44d5193cf2b827b03c64bc6", code);
                if(qqAccessToken==null)
                    return CodeContent.returnFailure("获取accessToken失败！");
                // 网页授权接口访问凭证
                accessToken = qqAccessToken.getAccessToken();
                System.out.println("accessToken"+accessToken);
                if(StringUtils.isEmpty(accessToken))
                    return CodeContent.returnFailure("获取accessToken失败！");
                // 用户标识
                openId = qqAccessToken.getOpenId();
                System.out.println("openId"+openId);
                // 获取用户信息
                QqUserInfo snsUserInfo = AdvancedUtil.getQqUserInfo(accessToken,"101442252" ,openId);
                System.out.println("snsUserInfo"+snsUserInfo.toString());
                if(snsUserInfo==null)
                    return CodeContent.returnFailure("获取QQ用户信息失败！");

                user=userService.getByQqOpenID(openId);
            }else {
                return CodeContent.returnFailure("授权类型错误！");
            }

            if(user==null){
                map.put("isOAuth",0);
                map.put("accessToken",accessToken);
                map.put("openId",openId);
                map.put("state",state);
                return CodeContent.returnSuccess(map);
            }
            else{
                if (user == null) {
                    return CodeContent.returnFailure("用户名不正确");
                }
                //判断是否是合法的用户
                if (UserState.Invalid.equals(user.getUserState())) {
                    return CodeContent.returnFailure("用户状态无效");
                }
                if(UserType.Normal.equals(user.getUserType())||UserType.Merchant.equals(user.getUserType())||UserType.ChildMerchant.equals(user.getUserType())){
                    //用户为前台账户
                }else {
                    return CodeContent.returnFailure("无权限登陆");
                }
                map.put("isOAuth",1);
                map.put("token", accessToken);
                Gson gson = new Gson();
                map.put("realName",user.getRealName());
                map.put("userTypeValue",user.getUserTypeValue());
                map.put("userPhone",user.getName());
                map.put("userType",user.getUserType()!=null?user.getUserType().toString():"");
                memcached.set(accessToken, 15*24*60*60, gson.toJson(user).toString()); //将对象和其token值存放在缓存中15天
                userService.userTokenLoginCheck(accessToken,user.getId());
                map.put("userId",user.getId());
                return CodeContent.getModelByCode(1,"sucess", map);
            }
        }
        // 跳转到index.jsp
        return CodeContent.returnFailure("失败！");
    }
    /**
     *
     * @param accessToken
     * @param openId
     * @param type
     * @return APP授权判断是否已经绑定授权过
     */
    @ResponseBody
    @RequestMapping(value = "/OAuthIsRegist3.json",produces = "application/json;charset=utf-8")
    public String OAuthIsRegist3(String companyCode,String accessToken,String openId,String type){
        ModelMap map=new ModelMap();
        User user=null;

        if(OAuthType.WX.toString().equals(type)) {
            WxUserInfo snsUserInfo = AdvancedUtil.getWxUserInfo(accessToken, openId);
            System.out.println("snsUserInfo" + snsUserInfo.toString());
            if (snsUserInfo == null)
                return CodeContent.returnFailure("获取微信用户信息失败！");

            user = userService.getByWxOpenID(snsUserInfo.getUnionid());
        }else if(OAuthType.QQ.toString().equals(type)) {
                QqUserInfo snsUserInfo = AdvancedUtil.getQqUserInfo(accessToken, "101442252", openId);
                System.out.println("snsUserInfo" + snsUserInfo.toString());
                if (snsUserInfo == null)
                    return CodeContent.returnFailure("获取QQ用户信息失败！");

                user = userService.getByQqOpenID(openId);
            }else
                return CodeContent.returnFailure("授权类型失败！");
            if(user==null){
                map.put("isOAuth",0);
                map.put("accessToken",accessToken);
                map.put("openId",openId);
                return CodeContent.returnSuccess(map);
            } else{
                if (user == null) {
                    return CodeContent.returnFailure("用户名不正确");
                }
                //判断是否是合法的用户
                if (UserState.Invalid.equals(user.getUserState())) {
                    return CodeContent.returnFailure("用户状态无效");
                }
                if(UserType.Normal.equals(user.getUserType())||UserType.Merchant.equals(user.getUserType())||UserType.ChildMerchant.equals(user.getUserType())){
                    //用户为前台账户
                }else {
                    return CodeContent.returnFailure("无权限登陆");
                }
                map.put("isOAuth",1);
                map.put("token", accessToken);
                Gson gson = new Gson();
                map.put("realName",user.getRealName());
                map.put("name",user.getName());
                map.put("userTypeValue",user.getUserTypeValue());
                map.put("userType",user.getUserType()!=null?user.getUserType().toString():"");
                memcached.set(accessToken, 15*24*60*60, gson.toJson(user).toString()); //将对象和其token值存放在缓存中15天
                userService.userTokenLoginCheck(accessToken,user.getId());
                map.put("userId",user.getId());
                return CodeContent.getModelByCode(1,"sucess", map);
            }
    }

    /**
     * 新用户手机验证码登录
     * @param accessToken 授权token
     * @param openId 唯一标识
     * @param userName 用户绑定手机号
     * @param code 用户手机验证码
     * @return 返回用户token
     */
    @ResponseBody
    @RequestMapping(value = "/OAuthNewRegist.json",produces="application/json;charset=UTF-8")
    public String OAuthNewRegist(String companyCode,String accessToken,String openId,String userName,String code,String type,String userId){
        ModelMap model=new ModelMap();
        String result = smsService.checkCode(Platform.Wap, userName, code,memcached.getCache());
        if(!"success".equals(result)){
            return CodeContent.returnFailure(result);
        }
        WxUserInfo wxUserInfo=null;
        QqUserInfo qqUserInfo=null;
        User user=null;
        User findUser=userDao.getByName(userName);
        int companyC=1;
        if(NumberUtils.isDigits(companyCode)){
            companyC=NumberUtils.toInt(companyCode);
        }
        if(findUser!=null)
            return CodeContent.returnFailure("该手机号已注册，请使用帐号密码登录或老用户授权");
        if(OAuthType.QQ.toString().equals(type)){
            qqUserInfo=AdvancedUtil.getQqUserInfo(accessToken,"101442252",openId);
            user=userService.OauthRegisterUser(userName,openId,qqUserInfo.getNickname(),qqUserInfo.getFigureurl_qq_2(),type,userId,companyC);
        }

        if(OAuthType.WX.toString().equals(type)){
            wxUserInfo=AdvancedUtil.getWxUserInfo(accessToken,openId);
            if(StringUtils.isEmpty(wxUserInfo.getUnionid()))
                return CodeContent.returnFailure("绑定失败！");
            user=userService.OauthRegisterUser(userName,wxUserInfo.getUnionid(),wxUserInfo.getNickname(),wxUserInfo.getHeadImgUrl(),type,userId,companyC);
        }

        model.put("token", accessToken);
        model.put("userId",user.getId());
        Gson gson = new Gson();
        memcached.set(accessToken, 15*24*60*60, gson.toJson(user).toString()); //将对象和其token值存放在缓存中15天
        userService.userTokenLoginCheck(accessToken,user.getId());
        return CodeContent.returnSuccess(model);
    }

    /**
     * 老用户绑定帐号密码登录
     * @param accessToken 授权token
     * @param openId 唯一标识
     * @param userName 用户帐号
     * @param passWord 用户密码
     * @return 返回用户token
     */
    @ResponseBody
    @RequestMapping(value = "/OAuthOldRegist.json",produces="application/json;charset=UTF-8")
    public String OAuthOldRegist(String companyCode,String accessToken,String openId,String userName,String passWord,String type){

        if (StringUtils.isBlank(userName) || StringUtils.isBlank(passWord)) {
            return CodeContent.returnFailure("用户名密码不能为空");
        }
        //判断是否是合法的用户  begin
        User user = userService.getByName(userName.trim());
        if (user == null) {
            return CodeContent.returnFailure("用户名不正确");
        }

        String password2 = user.getPassword();
        //判断密码是否正确
        if (!passWord.equals(password2)) {
            return CodeContent.returnFailure("密码错误");
        }
        //判断是否是合法的用户  end
        if (UserState.Invalid.equals(user.getUserState())) {
            return CodeContent.returnFailure("用户状态无效");
        }
        if(UserType.Normal.equals(user.getUserType())||UserType.Merchant.equals(user.getUserType())||UserType.ChildMerchant.equals(user.getUserType())){
            //用户为前台账户
        }else {
            return CodeContent.returnFailure("无权限登陆");
        }
        //进行绑定
        ModelMap model=new ModelMap();
        WxUserInfo wxUserInfo=null;
        QqUserInfo qqUserInfo=null;
        if(OAuthType.QQ.toString().equals(type)){
            if(StringUtils.isNotEmpty(user.getOpenId()))
                return CodeContent.returnFailure("该帐户已绑定QQ");
            qqUserInfo=AdvancedUtil.getQqUserInfo(accessToken,"101442252",openId);
            if(qqUserInfo!=null)
                user.setOpenId(openId);
            else
                return CodeContent.returnFailure("获取QQ授权失败！");
        }
        if(OAuthType.WX.toString().equals(type)){
            if(StringUtils.isNotEmpty(user.getWxOpenId()))
                return CodeContent.returnFailure("该帐户已绑定微信");
            wxUserInfo=AdvancedUtil.getWxUserInfo(accessToken,openId);
            if(wxUserInfo!=null)
                user.setWxOpenId(wxUserInfo.getUnionid());
            else
                return CodeContent.returnFailure("获取微信授权失败！");
        }
        userService.updateEntity(user);
        model.put("token", accessToken);
        model.put("userId",user.getId());
        Gson gson = new Gson();
        memcached.set(accessToken, 15*24*60*60, gson.toJson(user).toString()); //将对象和其token值存放在缓存中15天
        userService.userTokenLoginCheck(accessToken,user.getId());
        return CodeContent.returnSuccess(model);
    }
}


